/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    /**
     * p1 =  [1,2,4]
     * p2  = [1,3,4]
     * head
     * 1. 判断 p1 < p2
     *    head.next = p1
     *    p1++
     *
     * 2. p1 为空时，
     *    head.next = p2
     * @param list1
     * @param list2
     * @return
     */
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(-1);
        ListNode dummy = head;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                head.next = list1;
                list1 = list1.next;

            } else {
                head.next = list2;
                list2 = list2.next;
            }
            head = head.next;
        }
        if (list1 == null) {
            head.next = list2;
        }
        if (list2 == null) {
            head.next = list1;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        int[] array = {1,2,4};
        ListNode list1 = createList(array);

        int[] array2 = {1,3,4};
        ListNode list2 = createList(array2);

        Solution solution = new Solution();
        ListNode list3 = solution.mergeTwoLists(list1, list2);
    }

    public static ListNode createList(int[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        ListNode head = new ListNode(array[0]);
        ListNode pre = head;
        for (int i = 1; i < array.length; i++) {
            ListNode listNode = new ListNode(array[i]);
            pre.next = listNode;
            pre = listNode;
        }
        return head;
    }
}